package com.itheima.service.impl;

import com.itheima.common.R;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.PageBean;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author 小帅蓝
 * @Date 2022/6/15 13:56
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public R<Category> add(Category category) {

        int result = categoryMapper.add(category);
        if (result > 0) {
            return R.success(category);
        } else {
            return R.error("新增分类失败！");
        }
    }

    @Override
    public Integer getCount() {
        return categoryMapper.getCount();
    }

    @Override
    public PageBean queryAll(Integer page, Integer pageSize) {
        Integer offset = getOffset(page, pageSize);
        Integer total = getCount();
        List<Category> categoryList = categoryMapper.queryAll(offset, pageSize);
        return new PageBean(categoryList, total, pageSize, page);
    }

    @Override
    public R<String> delete(String id) {
        int result = categoryMapper.delete(id);
        if (result > 0) {
            return R.success("当前分类下关联了套餐，不能删除");
        } else {
            return R.error("删除分类失败！");
        }
    }

    @Override
    public R<Category> update(Category category) {
        int result = categoryMapper.update(category);
        if (result > 0) {
            return R.success(category);
        } else {
            return R.error("编辑分类失败！");
        }
    }

    @Override
    public List<Category> categoryList(Integer type) {
        return categoryMapper.selectAll(type);
    }


    /**
     * 获取起始页
     *
     * @param page     当前页
     * @param pageSize 每页条数
     * @return 每页起始数
     */
    public Integer getOffset(Integer page, Integer pageSize) {
        return (page - 1) * pageSize;
    }
}
